var user = "";
var selections = new Array();
var itemCounts = new Array();
var bankerFilterBox = 'undefined';
$(document).ready(function() {
	// while waiting for login.php response, fill header 
	//loadLoginBar("Loading...");
	
	doLogin();	
	console.debug(itemInfo);
	// use jquery addon tablesorter on item list
	$("#myTable").tablesorter({
		widthFixed: true, 
		widgetFilterChildRows: true,
		widgets: ['zebra', 'filter', 'stickyHeaders']
	});
	
		
	// listen for click on item table rows
	$('tr').click(rowClickHandler); 	
});

function clickTest() {
	console.debug("Top of clickTest()");
	bankerFilterBox =   $('input[data-col=0]');
	var bankerFilterCell = bankerFilterBox.parent();
	//bankerFilterBox.hide();
	var oldHtml = bankerFilterCell.html();
	
	
	var newHtml = '<select class="filter-dropdown" id="bankerFilter">';
    newHtml += '<option>Guilderaid</option>';
    newHtml += '<option>Guildeore</option>';
    newHtml += '<option>Guildelw</option>';
	newHtml += '</select>';
	bankerFilterCell.html(oldHtml+newHtml);
	$('#bankerFilter').change(function() {
		bankerFilterBox.val($('#bankerFilter').val());
		bankerFilterBox.change();
		console.debug(bankerFilterBox.val());
	});
	//console.debug(bankerFilerCell.html());
	//
	
	/*
	*/
    
}

function rowClickHandler(event) {
	// for FF
	var clickedClassName = 'undefined';
	if (typeof event.srcElement !== 'undefined') {		
		clickedClassName = event.srcElement.className;
	}
	if ((clickedClassName != "itemCountInput") && (clickedClassName != "itemName")) {
		//console.debug(event.srcElement.className);
		//console.debug(event);
		var currentID = $(this).attr('id');
		var myClass = $(this).attr("class");
		var cellID = $(this).children(".itemCount").attr("id");		
		var inputID = 'textBox-'+cellID;
		var itemCount = cellID.split('-')[2];
		//console.debug($(this).children(".itemCount").attr("id").split('-')[2]);
		
		//alert (myClass);
		if (myClass.indexOf("hilite") == -1) {
			//alert("added selection");
			
		cellHtml = '<input type="text" class="itemCountInput" id="';
		cellHtml += inputID;
		cellHtml += '" value="';
		cellHtml += itemCount;
		cellHtml += '" />';
		$(this).children(".itemCount").html(cellHtml);
			selections.push($(this).attr('id'));
		} else {
			//alert("removed selection");
			$(this).children(".itemCount").html(itemCount);
			for (var i = 0; i < selections.length; i++) {
				if (selections[i] == $(this).attr('id')) {
					selections.splice(i,1);					
					break;
				}
			}
		}			
		$(this).toggleClass('hilite');
		//console.debug(selections);
	}
}


		
	function doCheckout() {			
		console.debug("top of doCheckout()");
		
		urlString = "checkout.php"
		selections.map( function(item) {
			var itemCount = $("#"+item).children(".itemCount").children(".itemCountInput").val();
			console.debug(itemCount);
			itemCounts.push(itemCount)
			$("#"+item).toggleClass('hilite');
		});
		console.debug(itemCounts);
		$.ajax({			
		  url: urlString,
		  type: 'POST',
		  data: {"selections[]" :selections, "itemCounts[]":itemCounts, "user" : user},
		  success: function(data) {

		  }
		});
		
		resetSelections();
		
		//alert(item);//
		//var cellID = $(this).children(".itemCount").attr("id");					  
		//$('.result').html(data);
		//alert('Load was performed.');
		//console.debug(data);
	}
	
	function resetSelections() {
		console.debug("top of resetSelections()");
		selections.map( function(item) {		
			//alert(item);//
			itemCount = $("#"+item).children(".itemCount").children(".itemCountInput").attr("id").split('-')[3];
			console.debug(itemCount);
			 $("#"+item).toggleClass('hilite');
			 $("#"+item).children(".itemCount").html(itemCount);
			 //urlString += item;
			 //urlString +="&";
		});
		console.debug(selections);
		selections.splice(0,selections.length);
		itemCounts.splice(0,itemCounts.length);
		console.debug(selections);
	
	}
		
		function changePass() {
			console.debug("top of doLogin()");
			pwd0 = $("#pwd0").val();
			pwd1 = $("#pwd1").val();
			urlString = "login.php";
			$.ajax({
			  type: 'POST',
			  url: urlString,
			  data: { pass0: $("#pwd0").val(), pass1: $("#pwd1").val() },
			  dataType: 'json',
			  success: function(data) {
				if (data['code'] == '1') {
						//console.debug("code = 1");
						loadToolbar(data['msg']);
						//$("#checkoutBtn").click(doLogin);
						//$("#logoutBtn").click(doLogout);
					} else if (data['code'] == '2') {
						//console.debug(data);
						changeUserPass(data['msg']);
						
					} else {
						//console.debug("code = 0");
						loadLoginBar(data['msg']);
						
					}
			  }
			});			
		}
		

		function doLogin() {
				
				user = $("#user").val();
				pwd = $("#pwd").val();
				urlString = "login.php";
				$.ajax({
				  type: 'POST',
				  url: urlString,
				  data: { user: $("#user").val(), pass: $("#pwd").val() },
				  dataType: 'json',
				  success: function(data) {
					//console.debug(data);
					if (data['code'] == '1') {
						//console.debug("code = 1");
						user = data['user'];
						loadToolbar(data['msg']);
						//$("#checkoutBtn").click(doLogin);
						//$("#logoutBtn").click(doLogout);
					} else if (data['code'] == '2') {
						user = data['user'];
						//console.debug(data);
						changeUserPass(data['msg']);
						
					} else {
						//console.debug("code = 0");
						loadLoginBar(data['msg']);
					}
				  }
				});			
				
		}
		
		function doLogout() {
			urlString = "login.php";
			$.ajax({
			  type: 'POST',
			  url: urlString,
			  data: { logout: true },
			  dataType: 'json',
			  success: function(data) {
				console.debug(data);
				loadLoginBar(data['msg']);
			  }
			});			
		
		}
		
		
		//http://stackoverflow.com/questions/29943/how-to-submit-a-form-when-the-return-key-is-pressed
		//<div onKeyPress="checkSubmit(event)"/> 
		/*function onEnterLogin()
{
		   if(e && e.keyCode == 13)
		   {
			  document.forms[0].submit();
		   }
		}*/


		
		function changeUserPass(msg) {
			newHtml = '<h1 style="color:red;">NEW USER: YOU MUST CHANGE YOUR PASSWORD NOW.</h1>';
			//newHtml += '<div id="ajaxBusy"><p><img src="./images/loading.gif"></p></div>';
			newHtml = '<div id="header-buttons">';
			newHtml += '<div id="status">';
			newHtml += msg;
			newHtml += '</div>';
			newHtml += 'New Password:';
			newHtml += '<input type="password" id="pwd0" />';
			newHtml += 'Confirm:';
			newHtml += '<input type="password" id="pwd1" />';
			newHtml += '<BUTTON TYPE="button" id="changePassBtn" NAME="button" Value="Change Password">';
			newHtml += '</div>';
			
			$("#header").html(newHtml);		
			$("#changePassBtn").click(changePass);
			$("body, input, textarea").keypress(function(e){
				if(e.which==13) $("#changePassBtn").click();
			});
		}
		
		function loadLoginBar(msg) {			
			//newHtml = "<h1>Ye Olde Guilde Bank</h1><hr />";
			//newHtml += '<div id="ajaxBusy"><p><img src="./images/loading.gif"></p></div>';
			newHtml = '<div id="header-buttons">';
			newHtml += '<div id="status">';
			newHtml += msg;
			newHtml += '</div><br/>';
			newHtml += 'Name:<input type="text" id="user" value="Username" />'; //onclick="this.value=\'\';"
			newHtml += 'Password:<input type="password" id="pwd" value="password" />';
			newHtml += '<BUTTON TYPE="button" id="loginBtn" NAME="button" Value="Login">Login';
			newHtml += '</div>';
			
			$("#header").html(newHtml);
			$("#loginBtn").click(doLogin);
			$("body, input, textarea").keypress(function(e){
				if(e.which==13) $("#loginBtn").click();
			});
				
		}
		function loadToolbar(msg) {
			newHtml = '<div id="header-buttons">';
			newHtml += '<span id="userName">'+user+'</span>';
			newHtml += '<br/>';
			newHtml += '<div id="status">';
			newHtml += msg;
			newHtml += '</div><br/>';
			newHtml += "<BUTTON TYPE=\"button\" id=\"logoutBtn\" NAME=\"button\" Value=\"Logout\">Logout";
			newHtml += "<BUTTON TYPE=\"button\" id=\"resetBtn\" NAME=\"button\" Value=\"Reset\">Reset";
			newHtml += "<BUTTON TYPE=\"button\" id=\"checkoutBtn\" NAME=\"button\" Value=\"Checkout\">Checkout";
			newHtml += '</div>';
			
			$("#header").html(newHtml);
			$("#logoutBtn").click(doLogout);
			$("#resetBtn").click(resetSelections);
			$("#checkoutBtn").click(doCheckout);
			
		}

/* temp storage =P
	// Setup the ajax indicator
	//$('body').append('<div id="ajaxBusy"><p><img src="./images/loading.gif"></p></div>');
	//loadLoginBar('Loading...');
	//outputItemTable();
	// Ajax activity indicator bound to ajax start/stop document events

$(document).ajaxStart(function(){ 
  $('#ajaxBusy').show(); 
}).ajaxStop(function(){ 
  $('#ajaxBusy').hide();
});


	function outputItemTable() {
		
			$.ajax({
			  url: 'getItemData.php',
			  dataType: 'json',
			  success: function(data) {
			  $('thead').html('<tr><th>Banker</th><th>Count</th><th>Name</th><th>Quality</th></tr>');

				for (var i = 0; i < data.length; i++) {
					//console.debug(generateItemRow(data[i]));
					$("tbody").html($('tbody').html()+generateItemRow(data[i]));
					//alert(myStringArray[i]);
					//Do something
				}
				//$('main-content').html( $('main-content').html()+'</thead><tbody class="itemTableBody"></tbody></table>');
				$("#myTable").tablesorter({widgets: ['zebra']});
			  }
			});
		}
		
	function generateItemRow(item) {
		// each row identified by db primary key (id)
		returnStr = '<tr id="'+item['id']+'">';
		//returnStr = '<tr>';
		returnStr += '<td>'+item['banker']+'</td>';
		returnStr += '<td>'+item['itemCount']+'</td>';
		returnStr += '<td>'+item['itemName']+'</td>';
		returnStr += '<td>'+item['color']+'</td>';
		returnStr += '</tr>';
		
		return returnStr;
			
		
	}
	$(function() {
			//$('#header').css({'height': (($(window).height()) - 25)+'px'}); 
			//$('#main-content').css({'height': (($(window).height()) - 25)+'px'}); //magic number for footers
		    //$('#main-content').css({'width': (($(window).width()) - 250)+'px'});
			$(window).bind('resize', function(){
				//$('#main-content') .css({'height': (($(window).height()) - 25)+'px'});
				//$('#header').css({'height': (($(window).height()) - 25)+'px'}); 
				//$('#main-content').css({'width': (($(window).width()) - 250)+'px'});
				//alert('resized');
			});
		});
*/
		